<?php
namespace app\api\services;

use app\api\cache\CarefreeCache;
use app\api\consDir\CommunityConst;
use app\common\libs\Singleton;
use app\common\models\Carefree\CarefreeBusinessUser;
use app\common\models\Carefree\CarefreeDeductionAmountLog;
use app\common\models\Carefree\CarefreeDividendAmountLog;
use app\common\models\Carefree\CarefreeGoodsSku;
use app\common\models\Carefree\CarefreeMemberFinance;
use app\common\models\Carefree\CarefreeOrder;
use app\common\models\Carefree\CarefreeOrderGoods;
use app\common\models\Carefree\CarefreeProfitPoolLog;
use app\common\models\Carefree\CarefreeRedAmountLog;
use app\common\models\Carefree\CarefreeScoreAmountLog;
use app\common\models\Carefree\CarefreeSpeedAmountLog;
use app\common\models\Carefree\CarefreeWithdraw;
use app\common\models\Community\Community;
use app\common\models\Community\CommunityUser;
use app\common\models\Member\Finance;
use app\common\models\Member\Member;
use app\common\models\Member\MemberAgency;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CarefreeInfoService
{
    use Singleton;


    /**
     * 提现到个人余额
     * @param $userId
     * @param $communityAmount
     * @param $type
     * @return bool
     */
    public function withdraw($userId, $communityAmount, $type): bool
    {
        $config = CarefreeCache::getKeyData('carefree','withdraw');

        CarefreeMemberFinance::getInstance()->startTrans();
        try {
            //$charge = round($communityAmount * $fee * 0.01, 2);
            $orderNo = getNo('CW');
            //$charge = bcmul($communityAmount, $fee*0.01, 2);
            //$amount = bcsub($communityAmount, $charge, 2);
            $amount = $communityAmount;
            $repArr = [
                1 => $config['red_rep_rate'],
                2 => $config['earnings_rep_rate'],
            ];
            $repRate = $repArr[$type] ?? 0;
            if($repRate > 0){
                $msg = '会员提现，提现金额'.$repRate.'%存入抵扣券';
                $deduction = bcmul($amount,$repRate*0.01,2);
                $return = MemberService::getInstance()->addFinanceLog($userId, 'add', $deduction, 8, $msg, $orderNo);
                if (!$return) {
                    CarefreeMemberFinance::getInstance()->rollback();
                    return false;
                }
                $amount = bcsub($amount,$deduction,2);
            }

            $data = [
                'user_id' => $userId,
                'amount' => $amount,
                'money' => $communityAmount,
                'percent' => 0,
                'charge' => 0,
                'remark' => '兑换个人余额',
                'order_no' => $orderNo,
                'audit_at' => date('Y-m-d H:i:s'),
                'status' => 1, //成功
                'type' => $type
            ];
            $id = CarefreeWithdraw::getInstance()->insertGetId($data);
            if (!$id) {
                return false;
            }

            $data = [
                1 => '红包兑换',
                2 => '收益兑换',
            ];
            //红包兑换到个人余额，兑换100，扣除服务费20%，实到80
            $msg = $data[$type] . '个人余额，扣除抵扣券'.$repRate.'%，余额到账'.$amount;
            $return = CarefreeInfoService::getInstance()->addFinanceLog($userId, 'change', $communityAmount, $msg, $orderNo, $type);
            if (!$return) {
                CarefreeMemberFinance::getInstance()->rollback();
                return false;
            }

            $typeData = [
                1 => 'red_change',
                2 => 'earnings_change',
            ];

            //增加余额
            $msg = $data[$type] . '个人余额';
            $return = MemberService::getInstance()->addFinanceLog($userId, $typeData[$type], $amount, 1, $msg);
            if (!$return) {
                CarefreeMemberFinance::getInstance()->rollback();
                return false;
            }

        } catch (\Exception $e) {
            CarefreeMemberFinance::getInstance()->rollback();
            return false;
        }
        CarefreeMemberFinance::getInstance()->commit();
        return true;
    }


    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     * $fundType 0积分 1红包 2收益
     */
    public function addFinanceLog($userId, $logType, $amount, $msg = '', $orderNo = '', $fundType = 0,$sendScore = 0): bool
    {
        $total = bcadd($amount,$sendScore,4);
        if ($total <= 0) {
            return false;
        }

        $finance = $this->finance($userId);
        if (empty($finance)) {
            return false;
        }
        //0积分 1红包 2收益 4加速
        switch ($fundType){
            case 0:
                CarefreeInfoService::getInstance()->addScore($finance, $logType, $amount, $msg, $orderNo,$sendScore);
                break;
            case 1:
                CarefreeInfoService::getInstance()->addRedPacket($finance, $logType, $amount, $msg, $orderNo);
                break;
            case 2:
                CarefreeInfoService::getInstance()->addEarnings($finance, $logType, $amount, $msg, $orderNo);
                break;
            case 3:
                CarefreeInfoService::getInstance()->addDeduction($finance, $logType, $amount, $msg, $orderNo);
                break;
            case 4:
                CarefreeInfoService::getInstance()->addSpeed($finance, $logType, $amount, $msg, $orderNo);
                break;
        }
        return true;
    }

    public function addSpeed($finance, $type, $amount, $msg, $orderNo = ''): bool
    {
        if($amount <= 0){
            return false;
        }
        //判断是否减金额,
        $arr = [
            'change',
        ];

        $thisAmount = $finance['speedRate'];
        $status     = in_array($type, $arr) ? 2 : 1; //2减少

        if ($status == 1) {
            $config = CarefreeCache::getKeyData('carefree','base');;
            if($thisAmount <= 0){
                $rate = $config['base_rate'] ?? 0;
                if($rate > 0){
                    $thisAmount = bcadd($thisAmount,$config['base_rate'],2);
                }
            }
            $alterAmount = bcadd($thisAmount, $amount, 2);
        } else {
            $alterAmount = bcsub($thisAmount, $amount, 2);
        }

        $data = [
            'user_id'      => $finance['userId'],
            'status'       => $status,
            'remark'       => $msg . '，当前分红速度' . $alterAmount .'%',
            'log_type'     => $type,
            'this_amount'  => $thisAmount,
            'alter_amount' => $alterAmount,
            'amount'       => $amount,
            'order_no'     => $orderNo,
        ];
        CarefreeSpeedAmountLog::getInstance()->insert($data);
        if ($status == 1) {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('speed_rate', $amount)->update();
        } else {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->dec('speed_rate', $amount)->update();
        }

        return true;
    }

    public function addRedPacket($finance, $type, $amount, $msg, $orderNo = ''): bool
    {
        if($amount <= 0){
            return false;
        }
        //判断是否减金额,
        $arr = [
            'change', //提现到余额
        ];

        $thisAmount = $finance['redPacket'];
        $status     = in_array($type, $arr) ? 2 : 1; //2减少

        if ($status == 1) {
            $alterAmount = bcadd($thisAmount, $amount, 4);
        } else {
            $alterAmount = bcsub($thisAmount, $amount, 4);
        }

        $data = [
            'user_id'      => $finance['userId'],
            'status'       => $status,
            'remark'       => $msg . '，当前红包' . $alterAmount,
            'log_type'     => $type,
            'this_amount'  => $thisAmount,
            'alter_amount' => $alterAmount,
            'amount'       => $amount,
            'order_no'     => $orderNo,
        ];
        CarefreeRedAmountLog::getInstance()->insert($data);
        if ($status == 1) {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('red_packet', $amount)->update();
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('all_red_packet', $amount)->update();
        } else {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->dec('red_packet', $amount)->update();
        }

        return true;
    }

    public function addScore($finance, $type, $amount, $msg, $orderNo = '',$sendScore = 0): bool
    {
        $total = bcadd($amount,$sendScore,4);
        if($total <= 0){
            return false;
        }
        //判断是否减金额,
        $arr = [
            'change', //提现到余额
        ];
        $thisAmount = bcadd($finance['score'],$finance['sendScore'],4);
        $status     = in_array($type, $arr) ? 2 : 1; //2减少
        if ($status == 1) {
            $alterAmount = bcadd($thisAmount, $total, 4);
        } else {
            $alterAmount = bcsub($thisAmount, $total, 4);
        }

        $data = [
            'user_id'      => $finance['userId'],
            'status'       => $status,
            'remark'       => $msg . '，当前积分' . $alterAmount,
            'log_type'     => $type,
            'this_amount'  => $thisAmount,
            'alter_amount' => $alterAmount,
            'amount'       => $total,
            'order_no'     => $orderNo,
        ];
        CarefreeScoreAmountLog::getInstance()->insert($data);
        if ($status == 1) {
            if($amount > 0){
                CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('score', $amount)->update();
            }
            if($sendScore > 0){
                CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('send_score', $sendScore)->update();
            }
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('all_score', $total)->update();
        } else {
            if($amount > 0){
                CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->dec('score', $amount)->update();
            }
            if($sendScore > 0){
                CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->dec('send_score', $sendScore)->update();
            }
        }

        return true;
    }

    public function addEarnings($finance, $type, $amount, $msg, $orderNo = ''): bool
    {
        if($amount <= 0){
            return false;
        }
        //判断是否减金额,
        $arr = [
            'change', //提现到余额
        ];
        $thisAmount = $finance['earnings'];
        $status     = in_array($type, $arr) ? 2 : 1; //2减少

        if ($status == 1) {
            $alterAmount = bcadd($thisAmount, $amount, 4);
        } else {
            $alterAmount = bcsub($thisAmount, $amount, 4);
        }

        $data = [
            'user_id'      => $finance['userId'],
            'status'       => $status,
            'remark'       => $msg . '，当前收益' . $alterAmount,
            'log_type'     => $type,
            'this_amount'  => $thisAmount,
            'alter_amount' => $alterAmount,
            'amount'       => $amount,
            'order_no'     => $orderNo,
        ];
        CarefreeDividendAmountLog::getInstance()->insert($data);
        if ($status == 1) {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('earnings', $amount)->update();
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('all_earnings', $amount)->update();
        } else {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->dec('earnings', $amount)->update();
        }

        return true;
    }

    public function addDeduction($finance, $type, $amount, $msg, $orderNo = ''): bool
    {
        if($amount <= 0){
            return false;
        }
        //判断是否减金额,
        $arr = [
            'change', //提现到余额
            'buy', //购买商品抵扣
        ];
        $thisAmount = $finance['deduction'];
        $status     = in_array($type, $arr) ? 2 : 1; //2减少

        if ($status == 1) {
            $alterAmount = bcadd($thisAmount, $amount, 4);
        } else {
            $alterAmount = bcsub($thisAmount, $amount, 4);
        }

        $data = [
            'user_id'      => $finance['userId'],
            'status'       => $status,
            'remark'       => $msg . '，当前抵扣券' . $alterAmount,
            'log_type'     => $type,
            'this_amount'  => $thisAmount,
            'alter_amount' => $alterAmount,
            'amount'       => $amount,
            'order_no'     => $orderNo,
        ];
        CarefreeDeductionAmountLog::getInstance()->insert($data);
        if ($status == 1) {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('deduction', $amount)->update();
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->inc('all_deduction', $amount)->update();
        } else {
            CarefreeMemberFinance::getInstance()->where(['user_id' => $finance['userId']])->dec('deduction', $amount)->update();
        }

        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function finance($userId): array
    {
        $finance = CarefreeMemberFinance::getInstance()->where('user_id',$userId)->find();
        if(empty($finance)){
            $config = CarefreeCache::getKeyData('carefree','base');
            $rate = $config['base_rate'] ?? 0;
            $data = [
                'user_id' => $userId,
                'speed_rate' => $rate
            ];
            CarefreeMemberFinance::getInstance()->insert($data);
            $finance = CarefreeMemberFinance::getInstance()->where('user_id',$userId)->find();
        }
        return !empty($finance) ? $finance->toArray() : [];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function payCallback($payInfo): bool
    {
        $where = [
            ['order_no', '=', $payInfo['orderNo']],
            ['status','=',0] //未支付
        ];
        $ret = CarefreeOrder::getInstance()->where($where)->update(['status' => 1,'pay_at' => date('Y-m-d H:i:s')]);
        if(!$ret){
            return false;
        }
        $ret = CarefreeOrderGoods::getInstance()->where('order_no',$payInfo['orderNo'])->update(['status' => 1]);
        if(!$ret){
            return false;
        }
        $orderGoods = CarefreeOrderGoods::getInstance()->where('order_no',$payInfo['orderNo'])->field('sku_id,quantity')->find();
        $ret = CarefreeGoodsSku::getInstance()->where('id',$orderGoods['skuId'])->dec('goods_inventory',$orderGoods['quantity'])->update();
        if(!$ret){
            return false;
        }
        $order = CarefreeOrder::getInstance()->where('order_no',$payInfo['orderNo'])->find();

        if($order['deduction'] > 0){
            $deduction = Finance::getInstance()->where('user_id',$payInfo['userId'])->value('community_deduction');
            if($deduction >= $order['deduction']){
                MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'buy', 0, 8, '购买商品抵扣', $payInfo['orderNo'],1,0,$order['deduction']);
            }
        }
        $config = CarefreeCache::getKeyData('carefree','base');
        if(!isset($config['switch']) || $config['switch'] != 1){
            return true;
        }
        $price = $order['sellPrice'];
        if(isset($config['gift_type']) && $config['gift_type'] == 1){
            //平台抵扣券
            $msg = '无忧订单赠送抵扣券';
            $deduction = bcmul($price,$config['ping_deduction_rate']*0.01,2);
            MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'add', $deduction, 8, $msg, $payInfo['orderNo'],1,0,0);
        }else{
            //分红积分
            if($config['score_rate'] > 0){
                $money = bcmul($price,$config['score_rate']*0.01,2);
                $sendScore = bcsub($money,$price,2);
                CarefreeInfoService::getInstance()->addFinanceLog($payInfo['userId'],'add',$price,'购买商品赠送',$payInfo['orderNo'],0,$sendScore);
            }
        }

        if($config['gxz_rate'] > 0){
            $msg = '购买商品，赠送贡献值，订单号' . $payInfo['orderNo'];
            $money = bcmul($price,$config['gxz_rate']*0.01,2);
            MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'carefree', $money, 7, $msg, $payInfo['orderNo']);
        }

        $awardConfig = CarefreeCache::getKeyData('carefree','award');
        $count = CarefreeOrder::getInstance()->where('pay_at', 'not null')->where('user_id',$payInfo['userId'])->count();
        if($config['profit_pool_rate'] > 0){
            //存入分红池比例
            $money = bcmul($price,$config['profit_pool_rate']*0.01,4);
            $money = $this->halve($money,$awardConfig,0.5,$count);
            $data = [
                'user_id' => $payInfo['userId'],
                'order_price' => $price,
                'rate' => $config['profit_pool_rate'],
                'amount' => $money,
                'order_no' => $payInfo['orderNo'],
            ];
            CarefreeProfitPoolLog::getInstance()->insert($data);
        }

        $member = Member::getInstance()->where('id',$payInfo['userId'])->find();
        $agencyInfo = MemberService::getInstance()->getAgencyArr($member['provinceId'], $member['cityId'], $member['countryId'], $member['streetId']);

        //加入分润池
        $profit = $price;
        $profit = $this->halve($profit,$awardConfig,0.5,$count);
        MemberService::getInstance()->profitPoolLog($payInfo['userId'], $price, $payInfo['orderNo'], $profit, 6);

        //直推
        if($member['inviteId'] > 0) {
            $rate = $awardConfig['direct_rate'];
            $bonus = bcmul($price, $rate * 0.01, 4);
            $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
            $msg = '直推会员下单，获得收益'.$bonus;
            if($awardConfig['send_type'] == 0){
                CarefreeInfoService::getInstance()->addFinanceLog($member['inviteId'],'direct_earnings',$bonus,$msg,$payInfo['orderNo'],2);
            }else{
                MemberService::getInstance()->addFinanceLog($member['inviteId'], 'earnings_change', $bonus, 1, $msg, $payInfo['orderNo']);
            }

            //分红积分
            if($config['gift_type'] == 0){
                //加速
                if($count <= 1){
                    //新会员
                    $baseRate = $config['new_value'];
                }else{
                    //复购
                    $baseRate = $config['rep_value'];
                }

                $speedRate = CarefreeMemberFinance::getInstance()->where('user_id',$member['inviteId'])->value('speed_rate') ?: 0;
                $addSpeed = bcadd($speedRate,$baseRate,2);
                if($addSpeed > $config['max']){
                    $baseRate = bcsub($config['max'],$speedRate,2);
                }
                $userName = Member::getInstance()->where('id',$payInfo['userId'])->value('user_name');
                $msg = '推荐会员'.$userName.'下单消费，奖励分红速度';
                CarefreeInfoService::getInstance()->addFinanceLog($member['inviteId'],'add',$baseRate,$msg,$payInfo['orderNo'],4);
            }
        }
        //合伙人
        $commId = Community::getInstance()->where('comm_id', $member['commId'])->value('id');
        $where  = [
            ['community_id', '=', $commId],
            ['community_status', '=', CommunityConst::PERMANENT_STATUS],
        ];
        $community = CommunityUser::getInstance()->where($where)->find();
        if($awardConfig['partner_rate'] > 0 && !empty($community) && $community['userId']) {
            $rate = $awardConfig['partner_rate'];
            $bonus = bcmul($price, $rate * 0.01, 4);
            $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
            $msg = '会员下单，社区合伙人获得收益'.$bonus;
            if($awardConfig['send_type'] == 0){
                CarefreeInfoService::getInstance()->addFinanceLog($community['userId'],'partner_earnings',$bonus,$msg,$payInfo['orderNo'],2);
            }else{
                MemberService::getInstance()->addFinanceLog($community['userId'], 'earnings_change', $bonus, 1, $msg,$payInfo['orderNo']);
            }
        }
        //服务商
        $partnerInfo = MemberService::getInstance()->getMyPartnerInfo($payInfo['userId']);
        if(!empty($awardConfig['service']) && !empty($partnerInfo)) {
            $ids = $this->getDiGui($partnerInfo['partnerId']);
            $where = [
                ['user_id','in',$ids],
                ['status','in',[1,2,3,4]]
            ];
            //$orderNoArr = CarefreeOrder::getInstance()->where($where)->column('order_no');
            //$num = CarefreeOrderGoods::getInstance()->where('order_no','in',$orderNoArr)->sum('sell_price') ?: 0;
            $num = CarefreeOrder::getInstance()->where($where)->sum('sell_price') ?: 0;
            $rate = 0;
            $serviceArr = $awardConfig['service'];
            array_multisort(array_column($serviceArr,'num'),SORT_ASC,$serviceArr);
            foreach($serviceArr as $v){
                if(empty($v)){
                    continue;
                }
                if($num >= $v['num']){
                    $rate = $v['rate'];
                }
            }
            if($rate > 0){
                $bonus = bcmul($price, $rate * 0.01, 4);
                $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
                $msg = '会员下单，获得服务商收益'.$bonus;
                if($awardConfig['send_type'] == 0){
                    CarefreeInfoService::getInstance()->addFinanceLog($partnerInfo['partnerId'],'service_earnings',$bonus,$msg,$payInfo['orderNo'],2);
                }else{
                    MemberService::getInstance()->addFinanceLog($partnerInfo['partnerId'], 'earnings_change', $bonus, 1, $msg,$payInfo['orderNo']);
                }
            }
        }
        //平级服务商
        $userPingMember = Member::getInstance()->where('id',$payInfo['userId'])->find();
        $myPartner = MemberService::getInstance()->getMyPartner($userPingMember);
        if ($myPartner) {
            $ids = $this->getDiGui($myPartner['id']);
            $where = [
                ['user_id','in',$ids],
                ['status','in',[1,2,3,4]]
            ];
            //$orderNoArr = CarefreeOrder::getInstance()->where($where)->column('order_no');
            //$num = CarefreeOrderGoods::getInstance()->where('order_no','in',$orderNoArr)->sum('sell_price') ?: 0;
            $num = CarefreeOrder::getInstance()->where($where)->sum('sell_price') ?: 0;
            $rate = 0;
            $serviceArr = $awardConfig['ping_service'];
            array_multisort(array_column($serviceArr,'num'),SORT_ASC,$serviceArr);
            foreach($serviceArr as $v){
                if(empty($v)){
                    continue;
                }
                if($num >= $v['num']){
                    $rate = $v['rate'];
                }
            }
            if($rate > 0){
                $bonus = bcmul($price, $rate*0.01, 4);
                $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
                $msg   = '会员下单，获得平级服务商收益' .$bonus ;
                if($awardConfig['send_type'] == 0){
                    CarefreeInfoService::getInstance()->addFinanceLog($myPartner['id'],'earnings_change',$bonus,$msg,$payInfo['orderNo'],2);
                }else{
                    MemberService::getInstance()->addFinanceLog($myPartner['id'], 'earnings_change', $bonus, 1, $msg,$payInfo['orderNo']);
                }
            }
        }
        //省代理
        if ($agencyInfo['provinceUid'] > 0) {
            $rate = $awardConfig['province_rate'];
            $bonus = bcmul($price, $rate * 0.01, 4);
            $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
            $msg = '区域会员下单，获得收益'.$bonus;
            if($awardConfig['send_type'] == 0){
                CarefreeInfoService::getInstance()->addFinanceLog($agencyInfo['provinceUid'],'province_earnings',$bonus,$msg,$payInfo['orderNo'],2);
            }else{
                MemberService::getInstance()->addFinanceLog($agencyInfo['provinceUid'], 'earnings_change', $bonus, 1, $msg,$payInfo['orderNo']);
            }
        }
        //市代理
        if ($agencyInfo['cityUid'] > 0) {
            $rate = $awardConfig['city_rate'];
            $bonus = bcmul($price, $rate * 0.01, 4);
            $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
            $msg = '区域会员下单，获得收益'.$bonus;
            if($awardConfig['send_type'] == 0){
                CarefreeInfoService::getInstance()->addFinanceLog($agencyInfo['cityUid'],'city_earnings',$bonus,$msg,$payInfo['orderNo'],2);
            }else{
                MemberService::getInstance()->addFinanceLog($agencyInfo['cityUid'], 'earnings_change', $bonus, 1, $msg,$payInfo['orderNo']);
            }
        }
        //区/县代理
        if ($agencyInfo['countryUid'] > 0) {
            $rate = $awardConfig['area_rate'];
            $bonus = bcmul($price, $rate * 0.01, 4);
            $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
            $msg = '区域会员下单，获得收益'.$bonus;
            if($awardConfig['send_type'] == 0){
                CarefreeInfoService::getInstance()->addFinanceLog($agencyInfo['countryUid'],'area_earnings',$bonus,$msg,$payInfo['orderNo'],2);
            }else{
                MemberService::getInstance()->addFinanceLog($agencyInfo['countryUid'], 'earnings_change', $bonus, 1, $msg,$payInfo['orderNo']);
            }
        }
        //事业部
        $where = [
            ['status','=',1],
            ['deleted','=',0],
            ['income_rate','>',0]
        ];
        $businessList = CarefreeBusinessUser::getInstance()->where($where)->select();
        foreach($businessList as $v){
            $bonus = bcmul($price,$v['income_rate']*0.01,4);
            $bonus = $this->halve($bonus,$awardConfig,0.5,$count);
            $msg = '会员下单，获得收益'.$bonus;
            if($awardConfig['send_type'] == 0){
                CarefreeInfoService::getInstance()->addFinanceLog($v['userId'],'business_earnings',$bonus,$msg,$payInfo['orderNo'],2);
            }else{
                MemberService::getInstance()->addFinanceLog($v['userId'], 'earnings_change', $bonus, 1, $msg,$payInfo['orderNo']);
            }
        }

        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getDiGui(int $id = 0, array &$result = array()): array
    {
        $res = Member::getInstance()->where('invite_id', $id)->where('is_partner',0)->field('id')->select();
        foreach ($res as $v) {
            if ($v) {
                $result[] = $v;
                $this->getDiGui($v['id'], $result);
            }
        }
        //不包括自己
        //$arr[] = $id;
        return array_column($result, 'id');
    }

    /**
     * 复购减半
     * @param $bonus
     * @param $awardConfig
     * @param $rate
     * @param $count
     * @return mixed|string
     */
    public function halve($bonus,$awardConfig,$rate,$count){
        if($count > 1 && $awardConfig['rep_buy_reset'] == 0){
            $bonus = bcmul($bonus,$rate,4);
        }
        return $bonus;
    }

    public function halveRate($awardConfig,$rate,$count){
        if($count > 1 && $awardConfig['rep_buy_reset'] == 0){
            $rate = bcmul($rate,0.5,2);
        }
        return $rate;
    }

    /**
     * @param $userId
     * @param $price
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function limit($userId,$price): bool
    {
        $where = [
            ['user_id','=',$userId],
            ['status','in',[1,2,3,4]],
        ];
        $count = CarefreeOrder::getInstance()->where($where)->count();
        //不是复投不限制
        if($count == 0){
            return true;
        }
        $config = CarefreeCache::getKeyData('carefree','base');
        if(!isset($config['switch']) || $config['switch'] != 1){
            return true;
        }
        $role = [];
        if(!empty($config['limit'])){
            foreach($config['limit'] as $item){
                if(empty($item)){
                    continue;
                }
                if(isset($item['checked']) && $item['checked'] == 'on'){
                    $role[$item['id']] = $item['value'];
                }
            }
        }
        $level = 1;
        $where  = [
            ['community_status', '=', CommunityConst::PERMANENT_STATUS],
            ['user_id','=',$userId]
        ];
        $foreverCount = CommunityUser::getInstance()->where($where)->count();
        if($foreverCount > 0){
            $level = 2;
        }
        $where = [
            ['is_partner','=',1],
            ['id','=',$userId]
        ];
        $service = Member::getInstance()->where($where)->find();
        if($service){
            $level = 3;
        }

        $where = [
            ['user_id', '=', $userId],
            ['status', '=', 1],
            ['deleted', '=', 0],
        ];
        $agency = MemberAgency::getInstance()->where($where)->find();
        if($agency){
            //区
            if(in_array($agency['agencyType'],[3,4])){
                $level = 6;
            }
            //市
            if($agency['agencyType'] == 2){
                $level = 5;
            }
            //省
            if($agency['agencyType'] == 1){
                $level = 4;
            }
        }
        $memberScore = CarefreeMemberFinance::getInstance()->where('user_id',$userId)->value('score');
        $money = bcmul($price,$config['score_rate']*0.01,4);
        if(isset($role[$level]) && $role[$level] > 0){
            $score = bcadd($memberScore,$money,4);
            if($score > $role[$level]){
                return false;
            }
        }
        return true;
    }



}
